<?php

namespace App\Console\Commands\OpenShop;

use App\Library\FeiShu\SendFs;
use App\Models\Common\ConfigModel;
use App\Models\OpenShop\Organization\OpenShopRegionManageModel;
use App\Models\OpenShop\SiteLocation\OpenShopSiteLocationExamineLogModel;
use App\Models\OpenShop\SiteLocation\OpenShopSiteLocationModel;
use App\Service\OpenShop\Feishu\OrganizationManageService;
use App\Service\OpenShop\SiteLocation\SiteLocationService;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;

class ScrubSiteLocationHandler extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'openshop:scrub_site_location_handler';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '每天4点刷洗选址任务处理人';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $siteManager      = ConfigModel::getManager(ConfigModel::SITE_MANAGER);
        $siteSuperManager = ConfigModel::getManager(ConfigModel::SITE_SUPER_ADMIN);
        $verifyPersonnel  = ConfigModel::getManager(ConfigModel::VERIFY_PERSONNEL);

        OpenShopSiteLocationModel::query()
            ->whereIn('source', [OpenShopSiteLocationModel::SOURCE_OPEN_SHOP, OpenShopSiteLocationModel::SOURCE_HOUSING])
            ->where(function ($query) {
                $query
                    ->whereIn('clueStatus', [
                        OpenShopSiteLocationModel::CLUE_STATUS_11,
                        OpenShopSiteLocationModel::CLUE_STATUS_13,
                        OpenShopSiteLocationModel::CLUE_STATUS_0,
                    ])
                    ->orWhereIn('siteStatus', [
                        OpenShopSiteLocationModel::SITE_STATUS_2,
                        OpenShopSiteLocationModel::SITE_STATUS_10,
                        OpenShopSiteLocationModel::SITE_STATUS_22,
                        OpenShopSiteLocationModel::SITE_STATUS_11,
                    ]);
            })
            ->chunk(1000, function ($siteLocations) use ($siteSuperManager, $siteManager, $verifyPersonnel) {
                foreach ($siteLocations as $siteLocation) {

                    // 获取对应省区处理人
                    $provinceInfoBy = Cache::remember("provinceSiteManage:provinceCode-{$siteLocation->provinceCode}&cityCode-{$siteLocation->cityCode}", 60, function () use ($siteLocation){
                        return OrganizationManageService::getProvinceInfoByProvinceCode($siteLocation->provinceCode, $siteLocation->cityCode, 1);
                    });

                    $handlerArr     = [];
                    if ($siteLocation->source == OpenShopSiteLocationModel::SOURCE_OPEN_SHOP) {
                        // 获取战区负责人
                        $warZoneManage    = OpenShopRegionManageModel::getWarZoneInfoByProvinceCode($siteLocation->provinceCode)['userId'] ?? 0;

                        // 审批通过数量
                        $siteLocationExamineLogModel = OpenShopSiteLocationExamineLogModel::query()
                            ->where("type", OpenShopSiteLocationExamineLogModel::TYPE_DEFAULT)
                            ->where("orderNo", $siteLocation->orderNo)
                            ->where("source", OpenShopSiteLocationModel::SOURCE_OPEN_SHOP)
                            ->where('status', OpenShopSiteLocationExamineLogModel::STATUS_OK);

                        $siteLocationExamineLogCount = $siteLocationExamineLogModel->count();
                        $auditPosition               = $siteLocationExamineLogModel
                            ->pluck('createdByUid', 'position')
                            ->toArray();

                        switch ($siteLocation->siteStatus) {
                            case OpenShopSiteLocationModel::SITE_STATUS_2:
                                switch ($siteLocationExamineLogCount) {
                                    case 0:
                                        $handlerArr = array_unique(array_merge([$provinceInfoBy['operationUid'], $warZoneManage]));
                                        break;
                                    case 1:
                                        //获得已经审批的职位
                                        if (in_array(OpenShopSiteLocationExamineLogModel::POSITION_WAR_ZONE_MANAGER, array_keys($auditPosition))) {
                                            $handlerArr = [$provinceInfoBy['operationUid']];
                                        } else {
                                            $handlerArr = [$warZoneManage];
                                        }
                                        break;
                                    case 2:
                                        $handlerArr = $siteManager;
                                        break;
                                    case 3:
                                        $handlerArr = $verifyPersonnel;
                                        break;
                                }
                                break;
                            case OpenShopSiteLocationModel::SITE_STATUS_10:
                                $handlerArr = $siteManager;
                                break;
                            case OpenShopSiteLocationModel::SITE_STATUS_22:
                                $handlerArr = $verifyPersonnel;
                                break;
                            case OpenShopSiteLocationModel::SITE_STATUS_11:
                                $handlerArr = $siteSuperManager;
                                break;
                            case OpenShopSiteLocationModel::SITE_STATUS_3:
                            case OpenShopSiteLocationModel::SITE_STATUS_21:
                            case OpenShopSiteLocationModel::SITE_STATUS_0:
                                $handlerArr = [$siteLocation->developConsultantId];
                                break;
                        }

                        // switch ($siteLocationExamineLogCount) {
                        //     case OpenShopSiteLocationExamineLogModel::EXAMINE_COUNT_0:
                        //         $handlerArr = array_merge($siteManager, (isset($provinceInfoBy['operationUid']) ? [$provinceInfoBy['operationUid']] : []));
                        //         break;
                        //     case OpenShopSiteLocationExamineLogModel::EXAMINE_COUNT_1:
                        //         // 获得已经审批的职位
                        //         if (in_array(OpenShopSiteLocationExamineLogModel::POSITION_PROVINCE_EXAMINE, array_keys($auditPosition))) {
                        //             $handlerArr = $siteManager;
                        //         } else {
                        //             $handlerArr = isset($provinceInfoBy['operationUid']) ? [$provinceInfoBy['operationUid']] : [];
                        //         }
                        //         break;
                        //     case OpenShopSiteLocationExamineLogModel::EXAMINE_COUNT_2:
                        //         $handlerArr = $verifyPersonnel;
                        //         break;
                        //     case OpenShopSiteLocationExamineLogModel::EXAMINE_COUNT_3:
                        //         $handlerArr = $siteSuperManager;
                        //         break;
                        //     default:
                        // }
                    }
                    if ($siteLocation->source == OpenShopSiteLocationModel::SOURCE_HOUSING) {
                        if ($siteLocation->clueStatus == OpenShopSiteLocationModel::CLUE_STATUS_11) {
                            if (SiteLocationService::isSolicitBusinessManager($siteLocation->developConsultantId)) {
                                $approveProcedure     = OpenShopSiteLocationExamineLogModel::APPROVE_PROCEDURE["solicitBusinessManagerApprove"];
                                $existsApproveCount   = OpenShopSiteLocationExamineLogModel::getExistsApproveCount($siteLocation->orderNo);
                                $nextApproveRoleIndex = $existsApproveCount;
                                $handlerArr           = OpenShopSiteLocationExamineLogModel::getApproveProcedureUser(
                                    $approveProcedure[$nextApproveRoleIndex],
                                    $siteLocation,
                                );
                            } else {
                                $handlerArr = isset($provinceInfoBy['operationUid']) ? [$provinceInfoBy['operationUid']] : [];
                            }
                        } elseif ($siteLocation->clueStatus == OpenShopSiteLocationModel::CLUE_STATUS_13) {
                            $handlerArr = $siteManager;
                        } elseif ($siteLocation->clueStatus == OpenShopSiteLocationModel::CLUE_STATUS_0) {
                            $handlerArr = [];
                        } else {
                            $handlerArr = [$siteLocation->developConsultantId];
                        }
                    }
                    $this->info(implode(',', $handlerArr));
                    $handler = implode(',', $handlerArr);

                    $siteLocation->timestamps = false;
                    $siteLocation->handler    = $handler;
                    $siteLocation->save();
                }
            });
        SendFs::newRobot(SendFs::ROBOT_SITE_LOCATION)
            ->setTitleContent("选址处理人刷新完成", Carbon::now()->toDateTimeString())
            ->send();
    }
}
